package com.da.lon.wang.xlg.view;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.constants.PreferencesConfig;
import com.da.lon.wang.xlg.util.PreferenceUtils;
import com.da.lon.wang.xlg.util.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.ArrayWheelAdapter;

public class AddressPopupWindow extends PopupWindow implements
        OnWheelChangedListener, OnClickListener {

    private Context mContext;
    private View mMenuView;
    private TextView finishView;

    /**
     * 把全国的省市区的信息以json的格式保存，解析完成后赋值为null
     */
    private JSONObject mJsonObj;
    /**
     * 省的WheelView控件
     */
    private WheelView mProvince;
    /**
     * 市的WheelView控件
     */
    private WheelView mCity;
    /**
     * 区的WheelView控件
     */
    private WheelView mArea;

    /**
     * 所有省
     */
    private String[] mProvinceDatas;
    private String[] mProvinceDatasId;
    /**
     * key - 省 value - 市s
     */
    private Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
    private Map<String, String[]> mCitisDatasIdMap = new HashMap<String, String[]>();
    /**
     * key - 市 values - 区s
     */
    private Map<String, String[]> mAreaDatasMap = new HashMap<String, String[]>();
    private Map<String, String[]> mAreaDatasIdMap = new HashMap<String, String[]>();

    /**
     * 当前省的名称
     */
    private String mCurrentProviceName;

    private String mCurrentProviceId;
    /**
     * 当前市的名称
     */
    private String mCurrentCityName;

    private String mCurrentCityId;
    /**
     * 当前区的名称
     */
    private String mCurrentAreaName = "东城区";

    private String mCurrentAreaId = "500";

    private TextView locationView;
    private String adlocation;
    private int key;

    public AddressPopupWindow(Context context, TextView plocationView,
                              String adlocation, int key) {
        super(context);
        this.mContext = context;
        this.adlocation = adlocation;
        this.key = key;
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        mMenuView = inflater.inflate(R.layout.ouka_address_popupwindow, null);

        this.locationView = plocationView;

        // 设置SelectPicPopupWindow的View
        this.setContentView(mMenuView);
        // 设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(LayoutParams.FILL_PARENT);
        // 设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(LayoutParams.WRAP_CONTENT);
        // 设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        // 设置SelectPicPopupWindow弹出窗体动画效果
        this.setAnimationStyle(R.style.AnimBottom);
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        // 设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(dw);
        // mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
        mMenuView.setOnTouchListener(new OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {

                int height = mMenuView.findViewById(R.id.address_layout)
                        .getTop();
                int y = (int) event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (y < height) {
                        dismiss();
                    }
                }
                return true;
            }
        });

        finishView = (TextView) mMenuView.findViewById(R.id.address_finish);
        finishView.setOnClickListener(this);

//		initJsonData();
        mJsonObj = Utils.initJsonData(mContext);

        mProvince = (WheelView) mMenuView.findViewById(R.id.id_province);
        mCity = (WheelView) mMenuView.findViewById(R.id.id_city);
        mArea = (WheelView) mMenuView.findViewById(R.id.id_area);

        initDatas();

        mProvince.setViewAdapter(new ArrayWheelAdapter<String>(mContext,
                mProvinceDatas));
        // 添加change事件
        mProvince.addChangingListener(this);
        // 添加change事件
        mCity.addChangingListener(this);
        // 添加change事件
        mArea.addChangingListener(this);

        mProvince.setVisibleItems(7);
        mCity.setVisibleItems(7);
        mArea.setVisibleItems(7);
        updateCities();
        updateAreas();

        try {
            if (adlocation != null && adlocation.length() > 0
                    && !adlocation.contains("省,市,区")) {
                String[] split = adlocation.split(",");

                String provice_name = split[0];
                for (int i = 0; i < mProvinceDatas.length; i++) {
                    if (provice_name.contains(mProvinceDatas[i])) {
                        mProvince.setCurrentItem(i);
                    }
                }

                String city_name = split[1];
                String[] cities = mCitisDatasMap.get(provice_name);
                for (int i = 0; cities != null && i < cities.length; i++) {
                    if (city_name.contains(cities[i])) {
                        mCity.setCurrentItem(i);
                    }
                }
                if (split.length == 3) {
                    String area_name = split[2];
                    String[] areas = null;
                    if (key == 0) {//添加地址 0 为自动定位
                        areas = mAreaDatasMap.get(city_name.substring(0, city_name.length() - 1));
                        if (areas == null) {
                            areas = mAreaDatasMap.get(city_name);
                        }
                    } else if (key == 1) {//修改地址
                        areas = mAreaDatasMap.get(city_name);
                    }
                    for (int i = 0; areas != null && i < areas.length; i++) {
                        if (areas[i].equals(area_name)) {
                            mArea.setCurrentItem(i);
                        }
                    }
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

    /**
     * 根据当前的市，更新区WheelView的信息
     */
    private void updateAreas() {
        int pCurrent = mCity.getCurrentItem();
        mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
        mCurrentCityId = mCitisDatasIdMap.get(mCurrentProviceId)[pCurrent];
        String[] areas = mAreaDatasMap.get(mCurrentCityName);

        if (areas == null) {
            areas = new String[]{""};
        }
        mArea.setViewAdapter(new ArrayWheelAdapter<String>(mContext, areas));
        mArea.setCurrentItem(0);
    }

    /**
     * 根据当前的省，更新市WheelView的信息
     */
    private void updateCities() {
        int pCurrent = mProvince.getCurrentItem();
        mCurrentProviceName = mProvinceDatas[pCurrent];
        mCurrentProviceId = mProvinceDatasId[pCurrent];
        String[] cities = mCitisDatasMap.get(mCurrentProviceName);
        if (cities == null) {
            cities = new String[]{""};
        }
        mCity.setViewAdapter(new ArrayWheelAdapter<String>(mContext, cities));
        mCity.setCurrentItem(0);
        updateAreas();
    }

    /**
     * 解析整个Json对象，完成后释放Json对象的内存
     */
    private void initDatas() {
        try {
            JSONArray jsonArray = mJsonObj.getJSONArray("locationlist");
            mProvinceDatas = new String[jsonArray.length()];
            mProvinceDatasId = new String[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonP = jsonArray.getJSONObject(i);// 每个省的json对象
                String province = jsonP.getString("name");// 省名字

                String provinceId = jsonP.getString("id");

                mProvinceDatas[i] = province;

                mProvinceDatasId[i] = provinceId;

                JSONArray jsonCs = null;
                try {
                    /**
                     * Throws JSONException if the mapping doesn't exist or is
                     * not a JSONArray.
                     */
                    jsonCs = jsonP.getJSONArray("city");
                } catch (Exception e1) {
                    continue;
                }
                String[] mCitiesDatas = new String[jsonCs.length()];
                String[] mCitiesDatasId = new String[jsonCs.length()];
                for (int j = 0; jsonCs != null && j < jsonCs.length(); j++) {
                    JSONObject jsonCity = jsonCs.getJSONObject(j);
                    String city = jsonCity.getString("name");// 市名字

                    String cityId = jsonCity.getString("id");

                    mCitiesDatas[j] = city;

                    mCitiesDatasId[j] = cityId;
                    JSONArray jsonAreas = null;
                    try {
                        /**
                         * Throws JSONException if the mapping doesn't exist or
                         * is not a JSONArray.
                         */
                        jsonAreas = jsonCity.getJSONArray("county");
                    } catch (Exception e) {
                        continue;
                    }

                    String[] mAreasDatas = new String[jsonAreas.length()];// 当前市的所有区
                    String[] mAreasDatasId = new String[jsonAreas.length()];
                    for (int k = 0; null != jsonAreas && k < jsonAreas.length(); k++) {
                        String area = jsonAreas.getJSONObject(k).getString(
                                "name");// 区域的名称

                        String areaId = jsonAreas.getJSONObject(k).getString(
                                "id");

                        mAreasDatas[k] = area;
                        mAreasDatasId[k] = areaId;
                    }
                    mAreaDatasMap.put(city, mAreasDatas);
                    mAreaDatasIdMap.put(cityId, mAreasDatasId);
                }

                mCitisDatasMap.put(province, mCitiesDatas);
                mCitisDatasIdMap.put(provinceId, mCitiesDatasId);
            }

        } catch (JSONException e) {

        }
        mJsonObj = null;
    }

    /**
     * 从assert文件夹中读取省市区的json文件，然后转化为json对象
     */
//	private void initJsonData() {
//		try {
//			StringBuffer sb = new StringBuffer();
//			InputStream is = mContext.getAssets().open("location.json");
//			int len = -1;
//			byte[] buf = new byte[1024];
//			while ((len = is.read(buf)) != -1) {
//				sb.append(new String(buf, 0, len, "gbk"));
//			}
//			is.close();
//			mJsonObj = new JSONObject(sb.toString());
//		} catch (IOException e) {
//			e.printStackTrace();
//		} catch (JSONException e) {
//			e.printStackTrace();
//		}
//	}
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.address_finish:

                PreferenceUtils.getInstance().SetSettingString(
                        PreferencesConfig.PROVICE_NAME, mCurrentProviceName);
                PreferenceUtils.getInstance().SetSettingString(
                        PreferencesConfig.CITY_NAME, mCurrentCityName);
                PreferenceUtils.getInstance().SetSettingString(
                        PreferencesConfig.AREA_NAME, mCurrentAreaName);

                PreferenceUtils.getInstance().SetSettingString(
                        PreferencesConfig.PROVICE_ID, mCurrentProviceId);
                PreferenceUtils.getInstance().SetSettingString(
                        PreferencesConfig.CITY_ID, mCurrentCityId);
                if (mCurrentAreaName != null) {
                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.AREA_ID, mCurrentAreaId);
                } else {
                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.AREA_ID, "");
                }

                if (mCurrentAreaName == null) {
                    locationView.setText(mCurrentProviceName + ","
                            + mCurrentCityName);
                } else {
                    locationView.setText(mCurrentProviceName + ","
                            + mCurrentCityName + "," + mCurrentAreaName);
                }

                dismiss();

                break;

            default:
                break;
        }
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        // TODO Auto-generated method stub

        try {
            if (wheel == mProvince) {
                updateCities();
                if (mAreaDatasMap.get(mCurrentCityName) != null) {
                    mCurrentAreaName = mAreaDatasMap.get(mCurrentCityName)[0];
                }
                if (mAreaDatasIdMap.get(mCurrentCityId) != null) {
                    mCurrentAreaId = mAreaDatasIdMap.get(mCurrentCityId)[0];
                }
            } else if (wheel == mCity) {
                updateAreas();
                if (mAreaDatasMap.get(mCurrentCityName) != null) {
                    mCurrentAreaName = mAreaDatasMap.get(mCurrentCityName)[0];
                } else {
                    mCurrentAreaName = null;
                }
                if (mAreaDatasIdMap.get(mCurrentCityId) != null) {
                    mCurrentAreaId = mAreaDatasIdMap.get(mCurrentCityId)[0];
                }
            } else if (wheel == mArea) {
                String[] stri = mAreaDatasMap.get(mCurrentCityName);
                if (stri != null && stri.length != 0) {
                    mCurrentAreaName = mAreaDatasMap.get(mCurrentCityName)[newValue];
                    mCurrentAreaId = mAreaDatasIdMap.get(mCurrentCityId)[newValue];
                } else {
                    mCurrentAreaName = null;
                }

            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

}
